package cn.wjzhang.middle.modules.shortMes.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.wjzhang.core.beans.vo.Result;
import cn.wjzhang.middle.beans.request.MidShortMesRequest;
import cn.wjzhang.middle.modules.shortMes.service.MidShortMesService;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

/**
 * ========================
 * 功能描述
 *
 * @author wjzhang
 * @version v1.0
 * ========================
 * @date 2023/6/25 14:27
 */
@Service
@RefreshScope
public class MidShortMesServiceImpl implements MidShortMesService {

    @Value("${ali.accessKeyId}")
    private String accessKeyId;

    @Value("${ali.accessKeySecret}")
    private String accessKeySecret;

    @Value("${ali.signName}")
    private String signName;

    @Value("${ali.templateCode}")
    private String templateCode;

    @Override
    public Result<?> sendCode(MidShortMesRequest request) {
        // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
        Client client = null;
        try {
            Config config = new Config()
                    // 必填，您的 AccessKey ID
                    .setAccessKeyId(accessKeyId)
                    // 必填，您的 AccessKey Secret
                    .setAccessKeySecret(accessKeySecret);
            // 访问的域名
            config.endpoint = "dysmsapi.aliyuncs.com";
            client = new Client(config);
        } catch (Exception e) {
            return Result.error("初始化短信配置失败");
        }
        // 6位数验证码
        String verificationCode = RandomUtil.randomNumbers(6);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(request.getPhoneNumbers())
                .setTemplateParam(String.format("{\"code\":\"%s\"}", verificationCode));
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse smsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            System.out.println(smsResponse.body.getMessage());
            System.out.println(smsResponse.body.getBizId());
            System.out.println(smsResponse.body.getCode());
        } catch (TeaException error) {
            // 如有需要，请打印 error
            Common.assertAsString(error.message);
            return Result.error(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            Common.assertAsString(error.message);
            return Result.error(error.message);
        }
        return Result.ok(verificationCode);
    }

}
